package com.haixiaoke.smartLock.huixiangjia;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.haixiaoke.common.core.redis.RedisCache;
import com.haixiaoke.domain.SmartLock;
import com.haixiaoke.domain.SmartLockCard;
import com.haixiaoke.domain.SmartLockFace;
import com.haixiaoke.domain.SmartLockPwd;
import com.haixiaoke.service.*;
import com.haixiaoke.smartLock.base.SmartLockBasicsService;
import com.haixiaoke.smartLock.huixiangjia.util.AESUtil;
import com.haixiaoke.smartLock.huixiangjia.util.RandomPhoneNumGenerator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.math.BigInteger;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 慧享佳-智能锁接口
 */
@Slf4j
@Service
public class SmartLockHxjService implements SmartLockBasicsService {

    @Value("${huiXiangJia.url}")
    private String huiXiangJiaUrl;
    @Value(("${huiXiangJia.accountName}"))
    private String huiXiangJiaAccountName;
    @Value("${huiXiangJia.password}")
    private String huiXiangJiaPassword;
    @Autowired
    private RedisCache redisCache;


    @Autowired
    private ISmartLockCardService iSmartLockCardService;
    @Autowired
    private ISmartLockPwdService iSmartLockPwdService;
    @Autowired
    private ISmartLockFaceService iSmartLockFaceService;
    @Autowired
    private ISmartLockService iSmartLockService;

    /**
     * 获取慧享佳平台token
     *
     * @return token
     */
    public String getToken() {
        String token = redisCache.getCacheObject("sys_huiXiangJiaToken");
        if (StrUtil.isBlank(token)) {
            try {
                Map<String, Object> dataMap = new HashMap<>(4);
                dataMap.put("accountName", huiXiangJiaAccountName);
                dataMap.put("password", huiXiangJiaPassword);
                Map<String, Object> paramsMap = new HashMap<>(4);
                paramsMap.put("method", "apartmentLogin");
                paramsMap.put("data", dataMap);
                log.info("慧享佳--鉴权接口请求参数：{}", paramsMap);
                long time = System.currentTimeMillis();
                HttpResponse response = HttpRequest.post(huiXiangJiaUrl)
                        .header("Content-Version", "1.0")
                        .header("Content-Type", "text/json;charset=utf-8")
                        .body(JSONObject.toJSONString(paramsMap)).timeout(20000).execute();
                long useTime = System.currentTimeMillis() - time;
                log.info("慧享佳--鉴权接口响应参数：{}；useTime：{}", response.body(), useTime);
                if (HttpStatus.HTTP_OK == response.getStatus()) {
                    JSONObject jsonObject = JSONObject.parseObject(response.body());
                    String resultCode = jsonObject.getString("resultCode");
                    if ("0".equals(resultCode)) {
                        JSONObject data = jsonObject.getJSONObject("data");
                        token = data.getString("tokenId");
                        Integer expireTime = data.getInteger("expireTime");
                        redisCache.setCacheObject("sys_huiXiangJiaToken", token, expireTime / 10, TimeUnit.MILLISECONDS);
                    } else {
                        log.error("慧享佳--鉴权请求响应数据异常：{}", jsonObject);
                    }
                } else {
                    log.error("慧享佳--鉴权请求失败，code：{}；body:{}", response.getStatus(), response.body());
                }
            } catch (Exception e) {
                log.error("慧享佳--鉴权请求异常：{}", e.getMessage(), e);
            }
        }
        token = token.replace("\"", "");
        return token;
    }

    @Override
    public String getSmartLock(SmartLock smartLock) {
        String token = this.getToken();
        if (StrUtil.isEmpty(token)) {
            log.error("慧享佳--查询设备详细信息接口--token为空");
            return "0";
        }
        try {
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("roomId", smartLock.getSn());
            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("method", "apartmentRoomDetail");
            paramsMap.put("tokenId", token);
            paramsMap.put("data", dataMap);
            log.info("慧享佳--查询设备详细信息请求参数：{}", paramsMap);
            long time = System.currentTimeMillis();
            HttpResponse response = HttpRequest.post(huiXiangJiaUrl)
                    .header("Content-Version", "1.2")
                    .header("Content-Type", "text/json;charset=utf-8")
                    .body(JSONObject.toJSONString(paramsMap)).timeout(20000).execute();
            long useTime = System.currentTimeMillis() - time;
            log.info("慧享佳--查询设备详细信息响应参数：{}；useTime：{}", response.body(), useTime);
            if (HttpStatus.HTTP_OK == response.getStatus()) {
                JSONObject jsonObject = JSONObject.parseObject(response.body());
                String resultCode = jsonObject.getString("resultCode");
                if ("0".equals(resultCode)) {
                    if (jsonObject.getJSONObject("data").getString("lockMac").isEmpty()) {
                        // 智能锁MAC号为空
                        log.error("慧享佳--查询设备详细信息接口--智能锁MAC号为空");
                        return "0";
                    }
                    // 智能锁电量
                    String battery = jsonObject.getJSONObject("data").getString("electricNum");
                    return battery;
                } else {
                    log.error("慧享佳--查询设备详细信息请求响应数据异常：{}", jsonObject);
                }
            } else {
                log.error("慧享佳--查询设备详细信息请求失败，code：{}；body:{}", response.getStatus(), response.body());
            }
        } catch (Exception e) {
            log.error("慧享佳--查询设备详细信息请求异常：{}", e.getMessage(), e);
        }
        return "0";
    }

    @Override
    public String getSmartLockDetails(SmartLock smartLock) {
        return null;
    }

    @Override
    public String getLockPassword(SmartLock smartLock) {
        return null;
    }

    @Override
    public String getBluetooth(SmartLock smartLock) {
        return null;
    }

    @Override
    public String deleteBle(SmartLock smartLock) {
        return null;
    }

    @Override
    public String addBluetooth(SmartLock smartLock) {
        return null;
    }

    @Override
    public String addFingerprint(SmartLock smartLock) {
        return null;
    }

    @Override
    public String sendFingerprint(SmartLock smartLock) {
        return null;
    }

    @Override
    public String deleteFingerprint(SmartLock smartLock) {
        return null;
    }

    @Override
    public String offlinePassword(SmartLock smartLock) {
        return null;
    }

    @Override
    public String remoteUnlock(SmartLock smartLock) {
        return null;
    }

    @Override
    public String addPassword(SmartLock smartLock) {
        String token = this.getToken();
        if (StrUtil.isEmpty(token)) {
            log.error("慧享佳--授权智能锁用户密码接口--token为空");
            return "0";
        }
        try {
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("roomId", smartLock.getSn());
            String phoneNo = RandomPhoneNumGenerator.generatePhoneNum();
            dataMap.put("phoneNo", phoneNo);
            dataMap.put("keyName", "密码授权");
            dataMap.put("beginTime", smartLock.getStartTime().getTime() / 1000);
            dataMap.put("endTime", smartLock.getEndTime().getTime() / 1000);
            dataMap.put("password", AESUtil.encryptKey(token, smartLock.getPassword()));
            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("method", "apartmentAddPasswordKey");
            paramsMap.put("tokenId", token);
            paramsMap.put("data", dataMap);
            log.info("慧享佳--添加用户接口密码授权请求参数：{}", paramsMap);
            long time = System.currentTimeMillis();
            HttpResponse response = HttpRequest.post(huiXiangJiaUrl)
                    .header("Content-Version", "1.1")
                    .header("Content-Type", "text/json;charset=utf-8")
                    .body(JSONObject.toJSONString(paramsMap)).timeout(20000).execute();
            long useTime = System.currentTimeMillis() - time;
            log.info("慧享佳--添加用户接口密码授权响应参数：{}；useTime：{}", response.body(), useTime);
            if (HttpStatus.HTTP_OK == response.getStatus()) {
                JSONObject jsonObject = JSONObject.parseObject(response.body());
                String resultCode = jsonObject.getString("resultCode");
                if ("0".equals(resultCode)) {
                    // 维护数据库数据
                    smartLock.setKeyId(jsonObject.getJSONObject("data").getString("keyId"));
                    smartLock.setLockIdentifier(phoneNo);
                    this.insertSmartLockPwd(smartLock);
                    return "1";
                } else {
                    log.error("慧享佳--授权门锁用户密码请求响应数据异常：{}", jsonObject);
                }
            } else {
                log.error("慧享佳--授权门锁用户密码请求失败，code：{}；body:{}", response.getStatus(), response.body());
            }
        } catch (Exception e) {
            log.error("慧享佳--授权门锁用户密码请求异常：{}", e.getMessage(), e);
        }
        return "0";
    }


    @Override
    public String deletePwd(SmartLock smartLock) {
        String token = this.getToken();
        if (StrUtil.isEmpty(token)) {
            log.error("慧享佳--删除智能锁用户密码接口--token为空");
            return "0";
        }
        try {
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("phoneNo", smartLock.getLockIdentifier());
            dataMap.put("roomId", smartLock.getSn());
            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("method", "apartmentRoomSingleCheckOut");
            paramsMap.put("tokenId", token);
            paramsMap.put("data", dataMap);
            log.info("慧享佳--删除用户接口密码授权请求参数：{}", paramsMap);
            long time = System.currentTimeMillis();
            HttpResponse response = HttpRequest.post(huiXiangJiaUrl)
                    .header("Content-Version", "1.2")
                    .header("Content-Type", "text/json;charset=utf-8")
                    .body(JSONObject.toJSONString(paramsMap)).timeout(20000).execute();
            long useTime = System.currentTimeMillis() - time;
            log.info("慧享佳--删除用户接口密码响应参数：{}；useTime：{}", response.body(), useTime);
            if (HttpStatus.HTTP_OK == response.getStatus()) {
                JSONObject jsonObject = JSONObject.parseObject(response.body());
                String resultCode = jsonObject.getString("resultCode");
                if ("0".equals(resultCode)) {
                    // 维护数据库数据
                    iSmartLockPwdService.deleteSmartLockPwdBySnAndIdentification(smartLock.getSn(),smartLock.getIdentification());
                    return "1";
                } else {
                    log.error("慧享佳--删除门锁用户密码响应数据异常：{}", jsonObject);
                }
            } else {
                log.error("慧享佳--删除门锁用户密码请求失败，code：{}；body:{}", response.getStatus(), response.body());
            }
        } catch (Exception e) {
            log.error("慧享佳--删除门锁用户密码请求异常：{}", e.getMessage(), e);
        }
        return "0";
    }


    @Override
    public String addCard(SmartLock smartLock) {
        String token = this.getToken();
        if (StrUtil.isEmpty(token)) {
            log.error("慧享佳--授权智能锁用户门卡接口--token为空");
            return "0";
        }
        try {
            String cardNumber = smartLock.getCardNumber();
            // 是传16进制过来，需要转成10进制
            BigInteger bigInteger = new BigInteger(cardNumber, 16);
            cardNumber = String.valueOf(bigInteger);

            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("roomId", smartLock.getSn());
            String phoneNo = RandomPhoneNumGenerator.generatePhoneNum();
            dataMap.put("phoneNo", phoneNo);
            dataMap.put("keyName", "卡片授权");
            dataMap.put("beginTime", smartLock.getStartTime().getTime() / 1000);
            dataMap.put("endTime", smartLock.getEndTime().getTime() / 1000);
            dataMap.put("cardNum", AESUtil.encryptKey(token, cardNumber));
            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("method", "apartmentAddCardKey");
            paramsMap.put("tokenId", token);
            paramsMap.put("data", dataMap);
            log.info("慧享佳--添加用户门卡请求参数：{}", paramsMap);
            long time = System.currentTimeMillis();
            HttpResponse response = HttpRequest.post(huiXiangJiaUrl)
                    .header("Content-Version", "1.1")
                    .header("Content-Type", "text/json;charset=utf-8")
                    .body(JSONObject.toJSONString(paramsMap)).timeout(20000).execute();
            long useTime = System.currentTimeMillis() - time;
            log.info("慧享佳--添加用户门卡响应参数：{}；useTime：{}", response.body(), useTime);
            if (HttpStatus.HTTP_OK == response.getStatus()) {
                JSONObject jsonObject = JSONObject.parseObject(response.body());
                String resultCode = jsonObject.getString("resultCode");
                if ("0".equals(resultCode)) {
                    // 维护数据库数据
                    smartLock.setLockIdentifier(phoneNo);
                    smartLock.setKeyId(jsonObject.getJSONObject("data").getString("keyId"));
                    this.insertSmartLockCard(smartLock);
                    return "1";
                } else {
                    log.error("慧享佳--授权用户门卡请求响应数据异常：{}", jsonObject);
                }
            } else {
                log.error("慧享佳--授权用户门卡请求失败，code：{}；body:{}", response.getStatus(), response.body());
            }
        } catch (Exception e) {
            log.error("慧享佳--授权用户门卡请求异常：{}", e.getMessage(), e);
        }
        return "0";
    }


    @Override
    public String deleteCard(SmartLock smartLock) {
        String token = this.getToken();
        if (StrUtil.isEmpty(token)) {
            log.error("慧享佳--删除智能锁门卡接口--token为空");
            return "0";
        }
        try {
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("phoneNo", smartLock.getLockIdentifier());
            dataMap.put("roomId", smartLock.getSn());
            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("method", "apartmentRoomSingleCheckOut");
            paramsMap.put("tokenId", token);
            paramsMap.put("data", dataMap);
            log.info("慧享佳--删除用户门卡请求参数：{}", paramsMap);
            long time = System.currentTimeMillis();
            HttpResponse response = HttpRequest.post(huiXiangJiaUrl)
                    .header("Content-Version", "1.2")
                    .header("Content-Type", "text/json;charset=utf-8")
                    .body(JSONObject.toJSONString(paramsMap)).timeout(20000).execute();
            long useTime = System.currentTimeMillis() - time;
            log.info("慧享佳--删除用户门卡响应参数：{}；useTime：{}", response.body(), useTime);
            if (HttpStatus.HTTP_OK == response.getStatus()) {
                JSONObject jsonObject = JSONObject.parseObject(response.body());
                String resultCode = jsonObject.getString("resultCode");
                if ("0".equals(resultCode)) {
                    // 维护数据库数据
                    iSmartLockCardService.deleteSmartLockCardBySnAndIdentification(smartLock.getSn(),smartLock.getIdentification());
                    return "1";
                } else {
                    log.error("慧享佳--删除用户门卡请求响应数据异常：{}", jsonObject);
                }
            } else {
                log.error("慧享佳--删除用户门卡请求失败，code：{}；body:{}", response.getStatus(), response.body());
            }
        } catch (Exception e) {
            log.error("慧享佳--删除用户门卡请求异常：{}", e.getMessage(), e);
        }
        return "0";
    }

    @Override
    public String getUnlockKey(SmartLock smartLock) {
        String token = this.getToken();
        if (StrUtil.isEmpty(token)) {
            log.error("慧享佳--查询蓝牙开锁密钥接口--token为空");
            return "0";
        }
        try {
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("roomId", smartLock.getSn());
            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("method", "apartmentRoomDetail");
            paramsMap.put("tokenId", token);
            paramsMap.put("data", dataMap);
            log.info("慧享佳--查询蓝牙开锁密钥信息请求参数：{}", paramsMap);
            long time = System.currentTimeMillis();
            HttpResponse response = HttpRequest.post(huiXiangJiaUrl)
                    .header("Content-Version", "1.2")
                    .header("Content-Type", "text/json;charset=utf-8")
                    .body(JSONObject.toJSONString(paramsMap)).timeout(20000).execute();
            long useTime = System.currentTimeMillis() - time;
            log.info("慧享佳--查询蓝牙开锁密钥信息响应参数：{}；useTime：{}", response.body(), useTime);
            if (HttpStatus.HTTP_OK == response.getStatus()) {
                JSONObject jsonObject = JSONObject.parseObject(response.body());
                String resultCode = jsonObject.getString("resultCode");
                if ("0".equals(resultCode)) {
                    if (jsonObject.getJSONObject("data").getString("lockMac").isEmpty()) {
                        // 智能锁MAC号为空
                        log.error("慧享佳--查询蓝牙开锁密钥接口--智能锁MAC号为空");
                        return "0";
                    }
                    return jsonObject.getString("data");
                } else {
                    log.error("慧享佳--查询蓝牙开锁密钥信息请求响应数据异常：{}", jsonObject);
                }
            } else {
                log.error("慧享佳--查询蓝牙开锁密钥信息请求失败，code：{}；body:{}", response.getStatus(), response.body());
            }
        } catch (Exception e) {
            log.error("慧享佳--查询蓝牙开锁密钥信息请求异常：{}", e.getMessage(), e);
        }
        return "0";
    }

    @Override
    public String addFaceImage(SmartLock smartLock) {
        String token = this.getToken();
        if (StrUtil.isEmpty(token)) {
            log.error("慧享佳--授权人脸信息接口--token为空");
            return "0";
        }
        String uploadFile = this.uploadFile(token, smartLock.getFaceImage());
        if ("0".equals(uploadFile)) {
            return "0";
        }
        try {
            Long startTime = smartLock.getStartTime() == null ? new Date().getTime() : smartLock.getStartTime().getTime();
            Long endTime = smartLock.getEndTime() == null ? this.addTime(new Date()).getTime() : smartLock.getEndTime().getTime();
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("roomId", smartLock.getSn());
            String phoneNo = RandomPhoneNumGenerator.generatePhoneNum();
            dataMap.put("phoneNo", phoneNo);
            dataMap.put("keyName", "人脸授权");
            dataMap.put("beginTime", startTime / 1000);
            dataMap.put("endTime", endTime / 1000);
            dataMap.put("password", uploadFile);
            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("method", "apartmentAddFace");
            paramsMap.put("tokenId", token);
            paramsMap.put("data", dataMap);
            log.info("慧享佳--授权人脸信息请求参数：{}", paramsMap);
            long time = System.currentTimeMillis();
            HttpResponse response = HttpRequest.post(huiXiangJiaUrl)
                    .header("Content-Version", "1.3")
                    .header("Content-Type", "text/json;charset=utf-8")
                    .body(JSONObject.toJSONString(paramsMap)).timeout(20000).execute();
            long useTime = System.currentTimeMillis() - time;
            log.info("慧享佳--授权人脸信息响应参数：{}；useTime：{}", response.body(), useTime);
            if (HttpStatus.HTTP_OK == response.getStatus()) {
                JSONObject jsonObject = JSONObject.parseObject(response.body());
                String resultCode = jsonObject.getString("resultCode");
                if ("0".equals(resultCode)) {
                    // 维护数据库数据
                    smartLock.setLockIdentifier(phoneNo);
                    smartLock.setKeyId(jsonObject.getJSONObject("data").getString("keyId"));
                    this.insertSmartLockFace(smartLock);
                    return "1";
                } else {
                    log.error("慧享佳--授权人脸信息请求响应数据异常：{}", jsonObject);
                }
            } else {
                log.error("慧享佳--授权人脸信息请求失败，code：{}；body:{}", response.getStatus(), response.body());
            }
        } catch (Exception e) {
            log.error("慧享佳--授权人脸信息请求异常：{}", e.getMessage(), e);
        }
        return "0";
    }


    @Override
    public String deleteFace(SmartLock smartLock) {
        String token = this.getToken();
        if (StrUtil.isEmpty(token)) {
            log.error("慧享佳--删除授权人脸信息接口--token为空");
            return "0";
        }
        try {
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("phoneNo", smartLock.getLockIdentifier());
            dataMap.put("roomId", smartLock.getSn());
            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("method", "apartmentRoomSingleCheckOut");
            paramsMap.put("tokenId", token);
            paramsMap.put("data", dataMap);
            log.info("慧享佳--删除授权人脸信息请求参数：{}", paramsMap);
            long time = System.currentTimeMillis();
            HttpResponse response = HttpRequest.post(huiXiangJiaUrl)
                    .header("Content-Version", "1.2")
                    .header("Content-Type", "text/json;charset=utf-8")
                    .body(JSONObject.toJSONString(paramsMap)).timeout(20000).execute();
            long useTime = System.currentTimeMillis() - time;
            log.info("慧享佳--删除授权人脸信息响应参数：{}；useTime：{}", response.body(), useTime);
            if (HttpStatus.HTTP_OK == response.getStatus()) {
                JSONObject jsonObject = JSONObject.parseObject(response.body());
                String resultCode = jsonObject.getString("resultCode");
                if ("0".equals(resultCode)) {
                    // 维护数据库数据
                    iSmartLockFaceService.deleteSmartLockFaceBySnAndIdentification(smartLock.getSn(),smartLock.getIdentification());
                    return "1";
                } else {
                    log.error("慧享佳--删除授权人脸信息请求响应数据异常：{}", jsonObject);
                }
            } else {
                log.error("慧享佳--删除授权人脸信息请求失败，code：{}；body:{}", response.getStatus(), response.body());
            }
        } catch (Exception e) {
            log.error("慧享佳--删除授权人脸信息请求异常：{}", e.getMessage(), e);
        }
        return "0";
    }


    /**
     * 删除所有授权信息
     * @param sn
     * @return
     */
    public String deleteAll(String sn) {
        String token = this.getToken();
        if (StrUtil.isEmpty(token)) {
            log.error("慧享佳--删除所有授权信息接口--token为空");
            return "0";
        }
        try {
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("roomId", sn);
            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("method", "apartmentRoomCheckOut");
            paramsMap.put("tokenId", token);
            paramsMap.put("data", dataMap);
            log.info("慧享佳--删除所有授权信息请求参数：{}", paramsMap);
            long time = System.currentTimeMillis();
            HttpResponse response = HttpRequest.post(huiXiangJiaUrl)
                    .header("Content-Version", "1.1")
                    .header("Content-Type", "text/json;charset=utf-8")
                    .body(JSONObject.toJSONString(paramsMap)).timeout(20000).execute();
            long useTime = System.currentTimeMillis() - time;
            log.info("慧享佳--删除所有授权信息响应参数：{}；useTime：{}", response.body(), useTime);
            if (HttpStatus.HTTP_OK == response.getStatus()) {
                JSONObject jsonObject = JSONObject.parseObject(response.body());
                String resultCode = jsonObject.getString("resultCode");
                if ("0".equals(resultCode)) {
                    return "1";
                } else {
                    log.error("慧享佳--删除所有授权信息请求响应数据异常：{}", jsonObject);
                    return jsonObject.getString("reason");
                }
            } else {
                log.error("慧享佳--删除所有授权信息请求失败，code：{}；body:{}", response.getStatus(), response.body());
            }
        } catch (Exception e) {
            log.error("慧享佳--删除所有授权信息请求异常：{}", e.getMessage(), e);
        }
        return "0";
    }


    @Override
    public String getTaskList(SmartLock smartLock) {
        return null;
    }

    public Date addTime(Date nowTime) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(nowTime);
        calendar.add(Calendar.YEAR, 10);
        return calendar.getTime();
    }

    public void insertSmartLockPwd(SmartLock smartLock) {
        SmartLockPwd pwd = new SmartLockPwd();
        pwd.setSn(smartLock.getSn());
        pwd.setIdentification(smartLock.getIdentification());
        pwd.setGenerateType(SmartLockPwd.PASSWORD_GENERATE_TYPE_CUSTOM);
        pwd.setPassword(smartLock.getPassword());
        pwd.setStartTime(smartLock.getEndTime());
        pwd.setEndTime(smartLock.getEndTime());
        pwd.setKeyId(smartLock.getKeyId());
        pwd.setLockIdentifier(smartLock.getLockIdentifier());
        iSmartLockPwdService.insertSmartLockPwd(pwd);
    }


    public void insertSmartLockCard(SmartLock smartLock) {
        SmartLockCard idCard = new SmartLockCard();
        idCard.setSn(smartLock.getSn());
        idCard.setIdentification(smartLock.getIdentification());
        idCard.setCardType(smartLock.getCardType());
        idCard.setCardNumber(smartLock.getCardNumber());
        idCard.setStartTime(smartLock.getStartTime());
        idCard.setEndTime(smartLock.getEndTime());
        idCard.setKeyId(smartLock.getKeyId());
        idCard.setLockIdentifier(smartLock.getLockIdentifier());
        iSmartLockCardService.insertSmartLockCard(idCard);
    }


    public void insertSmartLockFace(SmartLock smartLock) {
        SmartLockFace face = new SmartLockFace();
        face.setSn(smartLock.getSn());
        face.setIdentification(smartLock.getIdentification());
        face.setFaceImage(smartLock.getFaceImage());
        face.setStartTime(smartLock.getStartTime());
        face.setEndTime(smartLock.getEndTime());
        face.setKeyId(smartLock.getKeyId());
        face.setLockIdentifier(smartLock.getLockIdentifier());
        iSmartLockFaceService.insertSmartLockFace(face);
    }
    /**
     * 人脸上传接口
     *
     * @param token    token
     * @param imageUrl 人脸路径
     * @return
     */
    public String uploadFile(String token, String imageUrl) {
        try {
            // 获取图片二进制
            File file = File.createTempFile("stream2file", ".jpg");
            byte[] imageData = HttpUtil.downloadBytes(imageUrl);
            if (ObjectUtil.isEmpty(imageData)){
                log.error("慧享佳代锁--人脸图片下载失败：{}", imageUrl);
                return "0";
            }
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(imageData);
            try (FileOutputStream out = new FileOutputStream(file)) {
                IOUtils.copy(byteArrayInputStream, out);
            }
            byte[] imageBytes = FileUtils.readFileToByteArray(file);
            String face = Base64.encodeBase64String(imageBytes);
            byteArrayInputStream.close();
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("password", face);
            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("method", "apartmentFaceImageUpload");
            paramsMap.put("tokenId", token);
            paramsMap.put("data", dataMap);
            log.info("慧享佳--人脸图片处理请求参数：{}", paramsMap);
            long time = System.currentTimeMillis();
            HttpResponse response = HttpRequest.post(huiXiangJiaUrl)
                    .header("Content-Version", "1.3")
                    .header("Content-Type", "text/json;charset=utf-8")
                    .body(JSONObject.toJSONString(paramsMap)).timeout(20000).execute();
            long useTime = System.currentTimeMillis() - time;
            log.info("慧享佳--人脸图片处理响应参数：{}；useTime：{}", response.body(), useTime);
            if (HttpStatus.HTTP_OK == response.getStatus()) {
                JSONObject jsonObject = JSONObject.parseObject(response.body());
                String resultCode = jsonObject.getString("resultCode");
                if ("0".equals(resultCode)) {
                    return jsonObject.getJSONObject("data").getString("password");
                } else {
                    log.error("慧享佳--人脸图片处理请求响应数据异常：{}", jsonObject);
                }
            } else {
                log.error("慧享佳--人脸图片处理请求失败，code：{}；body:{}", response.getStatus(), response.body());
            }
        } catch (Exception e) {
            log.error("慧享佳--人脸图片处理请求异常：{}", e.getMessage(), e);
        }
        return "0";
    }

}
